package zyutils

import (
	"bufio"
	"log"
	"os"
	"strings"
)

type ReadFile struct {
	scanner *bufio.Scanner
	handler *os.File
}

func (f *ReadFile) Open(file Path) {
	var err error
	f.handler, err = os.Open(string(file))
	if err != nil {
		log.Panicln(err)
	}
	f.scanner = bufio.NewScanner(f.handler)

}

func (f ReadFile) Close() {
	err := f.handler.Close()
	if err != nil {
		log.Panic(err)
	}
}

func (f ReadFile) ReadLine() (line string, isEOF bool) {
	if !f.scanner.Scan() {
		return line, true
	}
	return strings.TrimSpace(f.scanner.Text()), false

}

func (f ReadFile) ReadLines() (lines []string) {
	lines = make([]string, 0)
	for {
		line, isEOF := f.ReadLine()
		if isEOF {
			break
		}
		if len(line) == 0 {
			continue
		}
		lines = append(lines, line)
	}
	return lines
}

func NewReadFile[T string | Path](file T) ReadFile {
	f := ReadFile{}
	f.Open(Path(file))
	return f
}

type WriteFile struct {
	handler *os.File
}

func (f *WriteFile) Open(file Path) {
	var err error
	f.handler, err = os.Create(string(file))
	if err != nil {
		log.Panicln(err)
	}
}

func (f WriteFile) Close() {
	err := f.handler.Close()
	if err != nil {
		log.Panic(err)
	}
}

func (f WriteFile) WriteLine(line string) {
	_, err := f.handler.WriteString(line)
	if err != nil {
		log.Panic(err)
	}

}

func NewWriteFile[T string | Path](file T) WriteFile {
	f := WriteFile{}
	f.Open(Path(file))
	return f
}
